package com.xbdun.comweb.bmp.freemark;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;

import com.xbdun.comweb.bmp.BaseApplicationRunner;
import com.xbdun.comweb.bmp.constants.HtmlConstant;

import freemarker.template.SimpleHash;
import freemarker.template.Template;
import freemarker.template.TemplateException;
/**
 * freemark是否生成静态文件
 * @author zhanggt
 */
public class FreeMarkerViewUtil extends FreeMarkerView {
	private final static String HTML_DIR = "html";//静态文件文件夹
	@Override
	protected void doRender(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)throws Exception {
		// Expose model to JSP tags (as request attributes).
		exposeModelAsRequestAttributes(model, request);
		// Expose all standard FreeMarker hash models.
		SimpleHash fmModel = buildTemplateModel(model, request, response);
		if (logger.isDebugEnabled()) {
			logger.debug("Rendering FreeMarker 模版 [" + getUrl() + "] in FreeMarkerView '" + getBeanName() + "'");
		}
		// Grab the locale-specific version of the template.
		Locale locale = RequestContextUtils.getLocale(request);
		if (!model.containsKey(HtmlConstant.CREATE_HTML)||Boolean.FALSE.equals(model.get(HtmlConstant.CREATE_HTML))) {
			processTemplate(getTemplate(locale), fmModel, response);
		} else {
			createHTML(model.get(HtmlConstant.XBDUN_PAGE_NUMBER),getTemplate(locale), fmModel, request, response);
		}
	}
	//创建静态资源文件HTML
	private static final void createHTML(Object xbdunPageNumber,Template template, SimpleHash model, HttpServletRequest request,HttpServletResponse response) throws IOException, TemplateException, ServletException {
		// 站点根目录的绝对路径
		//String basePath = request.getSession().getServletContext().getRealPath("/");
		String requestHTML = getRequestHTML(xbdunPageNumber,request);
		// 静态页面绝对路径
		String htmlPath = BaseApplicationRunner.getXbdunStaticDir() + requestHTML;
		File htmlFile = new File(htmlPath);
		if (!htmlFile.getParentFile().exists()) {
			htmlFile.getParentFile().mkdirs();
		}
		if (!htmlFile.exists()) {
			htmlFile.createNewFile();
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
			// 处理模版
			template.process(model, out);
			out.flush();
			out.close();
		}
		/* 将请求转发到生成的htm文件 */
		request.getRequestDispatcher("/"+requestHTML).forward(request, response);
	}

	/**
	 * 生成静态文件的相对路径 
	 * @param xbdunPageNumber 当存在的时候，那么会在原来的地址上加上改名称
	 * @param request	请求参数
	 * @return /目录/*.htm
	 */
	private static final  String getRequestHTML(Object xbdunPageNumber,HttpServletRequest request) {
		// web应用名称,部署在ROOT目录时为空
		String contextPath = request.getContextPath();
		// web应用/目录/文件.do
		String requestURI = request.getRequestURI();
		int indexOf = requestURI.indexOf(".");
		if(indexOf>0){requestURI = requestURI.substring(0,indexOf);}
		// basePath里面已经有了web应用名称，所以直接把它replace掉，以免重复
		requestURI = requestURI.replaceFirst(contextPath, "");
		// 将.do改为.html,稍后将请求转发到此html文件
		requestURI = requestURI+((null!=xbdunPageNumber&&!"".equals(xbdunPageNumber+""))?xbdunPageNumber:"")+".html";
		return HTML_DIR+requestURI;
	}
}